<?php

class VideoService extends AbstractService
{

    protected static $_videoHosts = array(
	'vimeo' => array('www.vimeo.com', 'vimeo.com'),
	'youtube' => array('www.youtube.com', 'youtube.com')
    );

    protected function _init()
    {
	$this->setMapper(new VideoMapper());
    }

    public function getByReview(ReviewModel $model)
    {
	if (!$model->getId()) {
	    return false;
	}

	$cacheSlot = new CacheSlotsReviewFeatures($model, 'videos');
	if (($videos = $cacheSlot->load()) === false) {
	    $videos = $this->getMapper()->getAllFeatures($model->getId(), REVIEW_TABLE, VIDEO_TABLE);
	    if (!$videos) {
		$videos = array();
	    }
	    $cacheSlot->setData($videos)->save();
	}
	$model->setVideos($videos);
    }

    public function getByOpinion(OpinionModel $model)
    {
	if (!$model->getId()) {
	    return false;
	}

	$cacheSlot = new CacheSlotsOpinionFeatures($model, 'videos');
	if (($videos = $cacheSlot->load()) === false) {
	    $videos = $this->getMapper()->getAllFeatures($model->getId(), OPINION_TABLE, VIDEO_TABLE);
	    $cacheSlot->setData($videos)->save();
	}

	if ($videos) {
	    $model->setVideos($videos);
	}
    }

    public function getUrlType($url)
    {
	if (!$url) {
	    return false;
	}
	$url = parse_url($url);

	if (!isset($url['host']) || empty($url['host'])) {
	    return false;
	}

	foreach (self::$_videoHosts as $type => $hosts) {
	    if (in_array($url['host'], $hosts)) {
		return $type;
	    }
	}
	return false;
    }

    public function getVideoId($url, $type)
    {
	if (!$type || !$url) {
	    return false;
	}
	$method = 'get' . ucfirst($type) . 'Id';
	return call_user_func(array($this, $method), $url);
    }

    public function getYoutubeId($url)
    {
	if (!$url) {
	    return false;
	}
	$url = parse_url($url);
	if (!isset($url['query']) || (isset($url['query']) && empty($url['query']))) {
	    return false;
	}
	parse_str($url['query'], $res);

	if (!isset($res['v']) || (isset($res['v']) && empty($res['v']))) {
	    return false;
	}

	return $res['v'];
    }

    public function getVimeoId($url)
    {
	if (!$url) {
	    return false;
	}

	$videoId = basename($url);
	if (!$videoId) {
	    return false;
	}

	$data = UploadManager::getRemoteFile('http://vimeo.com/api/v2/video/' . $videoId . '.json');
	if (empty($data)) {
	    return false;
	}
	$data = json_decode($data);

	if (!isset($data[0]->id)) {
	    return false;
	}

	return $data[0]->id;
    }

    public function removeRelations($id)
    {
	if (!$id) {
	    return false;
	}
	$this->getMapper()->removeRelations($id);
    }

    public function onBeforeRemove(AbstractModel $model)
    {
	if ($model->getId()) {
	    $this->removeRelations($model->getId());
	}
	return parent::onBeforeRemove($model);
    }

}